package jp.bluecab.bluecabsystem.locrecserv.locrec;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.bluecab.bluecabsystem.common.PMF;
import jp.bluecab.bluecabsystem.locrecserv.classes.LocRecUser;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class UserServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(UserServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        String loginid, email;
        try {
            loginid = req.getParameter("loginid");
            email = user.getEmail();
        } catch (NumberFormatException ex) {
            return;
        }

        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            Query query = pm.newQuery(LocRecUser.class);
            query.setFilter("email==pEmail");
            query.setResult("count(this)");
            query.declareParameters("String pEmail");

            int count = (Integer) query.execute(email);
            if (count == 0) {
                LocRecUser u = new LocRecUser(loginid, email);
                pm.makePersistent(u);
            }
        } finally {
            pm.close();
        }

        resp.sendRedirect("/location/index.jsp");
    }
}
